'use strict';

const BaseController = require('../../core/base_controller');
const xlsx = require('xlsx');
const path = require('path');

class HelpQuestionsController extends BaseController {
  async updateStatus(){
    const { ctx } = this;
    const id = ctx.params.id;
    const status = ctx.request.body.status;
    const rules = {
      status: {
        type: 'enum',
        values: [1,0,true,false],
        required: true,
        message: '状态值错误',
      },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      const errors = err.errors.map(error => rules[error.field].message).map(el=>el.string).join();
      ctx.throw(400, errors);
    }
    let HelpQuestions =  await ctx.model.HelpQuestions.findByPk(id)
    if(!HelpQuestions) ctx.throw(400,'不存在该问题')
    await HelpQuestions.update({status});
    this.success(null, '状态更新成功');
  }
  // 获取问题列表
  async index() {
    const { ctx } = this;
    const { category, tags, question_title, page = 1, pageSize = 10 } = ctx.query;

    // 构建查询条件
    const where = {};
    if (category) where.category = category;
    if (tags) {
      // 标签模糊匹配
      where.tags = {
        [ctx.model.Sequelize.Op.like]: `%${tags}%`
      };
    }
    if (question_title) {
      where.question_title = {
        [ctx.model.Sequelize.Op.like]: `%${question_title}%`
      };
    }

    const { count, rows } = await ctx.model.HelpQuestions.findAndCountAll({
      where,
      order: [['created_at', 'DESC']],
      offset: (page - 1) * pageSize,
      limit: parseInt(pageSize),
    });

    this.success({
      list: rows,
      pagination: {
        total: count,
        current: parseInt(page),
        pageSize: parseInt(pageSize),
      },
    });
  }

  // 创建问题
  async create() {
    const { ctx } = this;
    const rules = {
      question_title: { type: 'string', required: true },
      question_answer: { type: 'string', required: true },
      category: { type: 'string', required: false },
      tags: { type: 'string', required: false },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      ctx.throw(400, '参数错误');
    }

    const question = await ctx.model.HelpQuestions.create(ctx.request.body);
    this.success(question);
  }

  // 更新问题
  async update() {
    const { ctx } = this;
    const question = await ctx.model.HelpQuestions.findByPk(ctx.params.id);

    if (!question) {
      ctx.throw(404, '问题不存在');
    }

    const rules = {
      question_title: { type: 'string', required: false },
      question_answer: { type: 'string', required: false },
      category: { type: 'string', required: false },
      tags: { type: 'string', required: false },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      ctx.throw(400, '参数错误');
    }

    await question.update(ctx.request.body);
    this.success(question);
  }

  // 删除问题
  async destroy() {
    const { ctx } = this;
    const question = await ctx.model.HelpQuestions.findByPk(ctx.params.id);

    if (!question) {
      ctx.throw(404, '问题不存在');
    }

    await question.destroy();
    this.success(null, '删除成功');
  }

  // 获取单个问题
  async show() {
    const { ctx } = this;
    const question = await ctx.model.HelpQuestions.findByPk(ctx.params.id);

    if (!question) {
      ctx.throw(404, '问题不存在');
    }

    this.success(question);
  }

  // 导入问题
  async import() {
    const { ctx } = this;

    // 获取上传的文件
    const file = ctx.request.files[0];
    if (!file) {
      ctx.throw(400, '请上传Excel文件');
    }

    // 验证文件类型
    const fileExt = path.extname(file.filename).toLowerCase();
    if (fileExt !== '.xlsx' && fileExt !== '.xls') {
      ctx.throw(400, '只支持.xlsx或.xls格式的Excel文件');
    }

    try {
      // 先获取问题分类的字典数据
      const dictionary = await ctx.model.Dictionary.findOne({
        where: { dict_key: 'interview_question_category' }  // 假设这是问题分类的字典key
      });

      if (!dictionary) {
        ctx.throw(400, '未找到问题分类字典');
      }

      // 获取所有分类选项
      const categoryOptions = await ctx.model.DictionaryDetail.findAll({
        where: { parent_id: dictionary.id },
        attributes: ['dict_key', 'dict_value']
      });

      // 创建分类值到key的映射
      const categoryMap = {};
      categoryOptions.forEach(option => {
        categoryMap[option.dict_value] = option.dict_key;
      });

      // 读取Excel文件
      const workbook = xlsx.readFile(file.filepath);
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      const data = xlsx.utils.sheet_to_json(worksheet);

      // 验证数据格式
      if (data.length === 0) {
        ctx.throw(400, 'Excel文件内容为空');
      }

      // 验证必要的列是否存在
      const firstRow = data[0];
      if (!firstRow['标题']) {
        ctx.throw(400, 'Excel文件格式错误，必须包含"标题"列');
      }

      // 转换数据格式并批量创建
      const questions = data.map(row => {
        // 获取分类的dict_key
        const categoryValue = row['分类'];
        const category = categoryValue ? categoryMap[categoryValue] : null;

        // 如果提供了分类但找不到对应的dict_key，抛出错误
        if (categoryValue && !category) {
          throw new Error(`无效的分类值: ${categoryValue}`);
        }

        return {
          question_title: row['标题'],
          question_answer: row['答案'],
          category: category, // 使用dict_key作为分类值
          tags: row['标签'] || null
        };
      });

      await ctx.model.HelpQuestions.bulkCreate(questions);

      this.success(null, `成功导入${questions.length}条数据`);
    } catch (error) {
      ctx.throw(500, '导入失败：' + error.message);
    } finally {
      // 清理临时文件
      await ctx.cleanupRequestFiles();
    }
  }
}

module.exports = HelpQuestionsController;
